package org.zero.onlinesubject.utils;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class JwtUtil {

    @Value("${jwt.secret")
    private String secret;

    @Value("${jwt.expireTime}")
    private long expireTime;

    public String createToken(Map<String,Object> map,String username){
        String token = null;
        try {
            token = Jwts.builder().setClaims(map)
                    .setAudience("Zero")
                    .setIssuer("Zero")
                    .setIssuedAt(new Date(System.currentTimeMillis()))
                    .signWith(SignatureAlgorithm.HS512, secret)
                    .setSubject(username)
                    .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                    .compact();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成token失败: "+e.getMessage());
        }
        return token;
    }

    public String createToken(String id){
        String token = null;
        try {
            token = Jwts.builder()
                    .setId(id)
                    .setIssuer("Zero")
                    .setIssuedAt(new Date(System.currentTimeMillis()))
                    .signWith(SignatureAlgorithm.HS512,secret)
                    .compact();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成token失败： "+e.getMessage());
        }
        return token;
    }

    public Claims parseToken(String token){
        Claims claims = null;
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(secret).parseClaimsJws(token);

            claims = claimsJws.getBody();
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {
            e.printStackTrace();
            log.error("token： "+token + "解析错误;"+e.getMessage());
        }
        return claims;
    }
}
